package com.zjh.controller;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: zjh
 * @Date: 2025/9/27 - 09 - 27 - 23:09
 * @Description: com.zjh.controller
 * @version: 1.0
 */
@RestController
@RequestMapping("/hello")
public class HelloController {
    // 用户必须有admin角色, 并且用户名必须为root
//    @PreAuthorize("hasRole('ADMIN') and authentication.name='root'")
    // 用户必须有READ_INFO权限
    @PreAuthorize("hasAuthority('READ_INFO')")
    @GetMapping
    public String hello1(){
        return "hello spring security";
    }
    // url携带的参数，必须为root
//    @PreAuthorize("authentication.name==#name")
//    @GetMapping
//    public String hello2(String name){
//        return "hello spring security"+name;
//    }
    @PreFilter(value = "filterObject.id%2==0",filterTarget = "users")
    @GetMapping("/users")
    public void addUsers(@RequestBody List<User> users){
        System.out.println( users);
    }
    @PostAuthorize("returnObject.id==2")
    @GetMapping("/userId")
    public User getUserById(Integer id){
        User user = new User();
        user.setId(id);
        user.setName("zjh");
        return user;
    }

    @PostFilter("filterObject.id%2==0")
    @GetMapping("/lists")
    public List<User> getUsers(){
        ArrayList<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++){
            users.add(new User(i,"blr"+i));
        }
        return users;
    }

    @Secured("ROLE_USER")// 用户必须有USER角色,只能判断角色这个注解
    @GetMapping("/secured")
    public String secured(){
        return "secured";
    }

    @Secured({"ROLE_ADMIN","ROLE_USER"})// 用户必须有ADMIN或者USER角色,其中一个即可
    @GetMapping("/secureds")
    public String secureds(){
        return "secureds";
    }
    @PermitAll// 用户可以任意访问
    @GetMapping("/permitAll")
    public String permitAll(){
        return "permitAll";
    }
    @DenyAll // 用户不可以访问
    @GetMapping("/denyAll")
    public String denyAll(){
        return "denyAll";
    }
    @RolesAllowed({"ROLE_ADMIN","ROLE_USER"})// 用户必须有ADMIN或者USER角色,其中一个即可
    @GetMapping("/rolesAllowed")
    public String rolesAllowed(){
        return "rolesAllowed";
    }
    

}
